package com.health.viewscontrols.medical.device.xhdb;

import android.bluetooth.BluetoothGatt;
import android.os.Handler;
import android.util.Log;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.clj.fastble.utils.HexUtil;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.nova.health.ble.callback.OnDeviceConnectChangedListener;
import com.novabluetooth.data.DeviceShowSaveData;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 百捷三合一
 */
public class LysunXHDBActivity extends BaseDeviceActivity {

    public final static UUID UUID_SERVICE =
            UUID.fromString("0000fee9-0000-1000-8000-00805f9b34fb");//蓝牙设备的Service的UUID --0000ffe0
    public final static UUID UUID_NOTIFY =
            UUID.fromString("d44bc439-abfd-45a2-b575-925416129601");//蓝牙设备的Characteristic的UUID --0000ffe1
    public final static UUID UUID_WRITE =
            UUID.fromString("d44bc439-abfd-45a2-b575-925416129600");//蓝牙设备的Characteristic的UUID --0000ffe1


    private boolean isParseDataSuccess = false;
    @Override
    public void doBusiness() {
        tv_operation_tips.setText(com.nova.health.ble.R.string.xhdb2);

        BleManager.getInstance().init(getApplication());

        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                .setDeviceMac(deviceEnum.getMac())
                .setScanTimeOut(10000)              // 扫描超时时间，可选，默认10秒；小于等于0表示不限制扫描时间
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);

        mBleDevice.setConnectChangedListener(new OnDeviceConnectChangedListener() {
            @Override
            public void onConnected() {
                Log.e(TAG, "onConnected: ");
                isConnected = true;
                runOnUiThread(() -> {
                    blueToothState.setText("蓝牙已连接");
                    showProgressDialog("等待接收数据" + deviceEnum.getTitle() + "数据");
                });
            }

            @Override
            public void onDisconnected() {
                isConnected = false;
                Log.e(TAG, "onDisconnected: ");
                cancelProgressDialog();
                runOnUiThread(() -> {
                    blueToothState.setText("蓝牙连接失败");
                });
            }
        });
    }

    @Override
    public void startDevice() {
        if (!isConnected) {
            isParseDataSuccess = false;
            BleManager.getInstance().scan(new BleScanCallback() {
                @Override
                public void onScanStarted(boolean success) {
                }

                @Override
                public void onLeScan(BleDevice bleDevice) {
                    super.onLeScan(bleDevice);
                }

                @Override
                public void onScanning(BleDevice bleDevice) {
                    if (bleDevice != null && bleDevice.getMac() != null && deviceEnum.getMac().equals(bleDevice.getMac())) {
                        connDevice();
                    }
                }

                @Override
                public void onScanFinished(List<BleDevice> scanResultList) {

                }
            });
        } else {
            blueToothState.setText("蓝牙已连接");
            showProgressDialog("等待接收数据" + deviceEnum.getTitle() + "数据");
        }
    }

    private void connDevice() {
        showProgressDialog("开始连接设备");
        BleManager.getInstance().connect(deviceEnum.getMac(), new BleGattCallback() {
            @Override
            public void onStartConnect() {
                blueToothState.setText("开始连接蓝牙");
                Log.e(TAG, "*********开始连接**************");
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                Log.e(TAG, "*********连接失败**************" + exception.toString());
                isConnected = false;
                blueToothState.setText("蓝牙连接失败");
                cancelProgressDialog();
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                Log.e(TAG, "*********连接成功**************");
                isConnected = true;
                blueToothState.setText("蓝牙已连接");
                showProgressDialog("等待接收数据" + deviceEnum.getTitle() + "数据");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        bleNotify(bleDevice, UUID_SERVICE.toString(), UUID_NOTIFY.toString());
                    }
                }, 300);
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                Log.e(TAG, "*********连接中断**************" + status);
                isConnected = false;
                blueToothState.setText("蓝牙已断开");
                cancelProgressDialog();
            }
        });
    }

    private void bleNotify(BleDevice bleDevice, String uuid_service, String uuid_characteristic_notify) {
        BleManager.getInstance().notify(
                bleDevice,
                uuid_service,
                uuid_characteristic_notify,
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        // 打开通知操作成功
                    }

                    @Override
                    public void onNotifyFailure(BleException exception) {
                        // 打开通知操作失败
                    }

                    @Override
                    public void onCharacteristicChanged(final byte[] data) {
                        // 打开通知后，设备发过来的数据将在这里出现
                        Log.e(TAG, "onCharacteristicChanged: " + "收到data==" + Arrays.toString(data));
                        Log.e(TAG, "onCharacteristicChanged: "  +  HexUtil.formatHexString(data));
                        try {
                            if (!isParseDataSuccess) {
                                String dataStr = new String(data);
                                String[] strs = dataStr.replaceAll("\n", "")
                                        .replaceAll(" ", "")
                                        .replaceAll("g/dLHC", "")
                                        .split("HB:");

                                tv_result.setText("血红蛋白值：" + strs[1] + " g/dL");
                                DeviceShowSaveData.getDataShow(strs[1] + "", "LYSUN BHM-101");
                                cancelProgressDialog();
                                disconnectDevice();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            cancelProgressDialog();
                            tv_result.setText("数据解析异常，请重新测量！");
                        }
                    }
                });
    }

    @Override
    public void update(String hexStr) {
        Log.e(TAG, "update: " + hexStr );

    }

    @Override
    public void disconnectDevice() {
        try {
            cancelProgressDialog();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
